package com.hollysys.usersync.interceptor;


import com.alibaba.fastjson2.JSONObject;
import com.hollysys.usersync.entity.platform.LoginRequest;
import com.hollysys.usersync.feign.LoginServiceInvoker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 获取平台TOKEN
 *
 * @author Jeremy Yim
 * @date 2023-04-06
 */
@Component
@Slf4j
@EnableScheduling
public class AppToken implements ApplicationRunner {

    @Resource
    private LoginServiceInvoker systemService;

    @Value("${hollysys.platform.clientId}")
    private String userName;

    @Value("${hollysys.platform.secretKey}")
    private String userPassword;

    private static String token;

    @Override
    public void run(ApplicationArguments args) {
        try {
            refreshToken();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Token获取失败！");
        }
    }

    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void refreshToken() {
        log.info("开始刷新TOKEN");
        LoginRequest loginAccount = LoginRequest.builder().username(userName).password(userPassword)
                .clientId("m7it").state("1").responseType("code").build();
        JSONObject response = systemService.getCode(loginAccount);
        if (ObjectUtils.isEmpty(response.getString("code"))) {
            throw new RuntimeException("Code获取失败！");
        }
        response = systemService.getToken(response.getString("code"));
        token = "Bearer " + response.getString("access_token");
    }

    public static String getToken() {
        return token;
    }
}
